/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');
var async  = require( 'async'); // 同步控制


// Schema 结构
var ItbImageModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`img_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '图像ID',
  //`user_type` int(1) NOT NULL DEFAULT '0' COMMENT '0后台; 1用户',
  //`user_id` bigint(20) NOT NULL COMMENT '用户ID',
  //`img_name` varchar(50) DEFAULT NULL COMMENT '文件名',
  //`url` varchar(500) NOT NULL DEFAULT '' COMMENT 'URL地址',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',
  //`url_qn` varchar(500) NOT NULL DEFAULT '' COMMENT 'qiniu URL地址',

};
ItbImageModel.prototype = new ItbBaseModel();

// 取得表名
ItbImageModel.prototype.getTableName = function(){
    return 'itb_image';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbImageModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'img_id='+this.img_id;
}

// 带关键字查找
// 参数：key, 关键字
// callback 参数：
//                error：错误
//                count：找到的个数
ItbImageModel.prototype.findCountFromDBWithKey = function(key, callback){
    var THIS = this;
    var tableName = this.getTableName();
    var whereCondition = THIS.getWhereCondition() + ' and img_name like "%'+key+'%"';
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = "select count(*) as itemCount from "+tableName+" t1 where "+whereCondition;
        var sqlValue = [];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            var total=0;
            if(error) {
                console.log(error);
            } else if (items) {
                console.log('find item');
                total = items[0].itemCount;
            } else{
                console.log('find no one');
            }
            // 回调
            callback(error, total);
        });

    });

}

// 带关键字查找
// 参数：key, 关键字
// callback 参数：
//                error：错误
//                items：找到所有对象
ItbImageModel.prototype.findFromDBWithKey = function(key, callback,skipCnt,pageSize){
    var THIS = this;
    var tableName = this.getTableName();
    var whereCondition = THIS.getWhereCondition() + ' and img_name like "%'+key+'%"';
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = "select *  from "+tableName+" t1 where "+whereCondition;
        sql+=" ORDER BY update_time DESC, img_id DESC  ";
        if(typeof skipCnt!='undefined' && skipCnt != null && typeof pageSize!='undefined' && pageSize != null){
            sql += " limit " + Number(skipCnt) + "," + Number(pageSize);
        }
        var sqlValue = [];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });

}

// 逻辑删除图片
// callback 参数：
//                error：错误
ItbImageModel.prototype.logicDeleteImage = function(user_id,img_id,callback){

    var THIS = this;
    var tableName = this.getTableName();
    //mysql update
    pool.pool.getConnection(function(err, connection) {
        // Use the connection

        var sql = 'UPDATE '+tableName+
            ' SET del_flg=1, update_time=sysdate(), update_by='+user_id+
            ' WHERE img_id='+img_id+' and user_id='+user_id;
        var sqlValue = [ THIS ];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error) {
                console.log('ItbBaseModel.prototype.updateToDB error:'+error);
                callback(error);
            } else {
                callback(null);
            }
        });
    });
}

// 按更新时间逆序获取
// 参数：key, 关键字
// callback 参数：
//                error：错误
//                items：找到所有对象
ItbImageModel.prototype.findImgByUser = function(callback,skipCnt,pageSize){
    var THIS = this;
    var tableName = this.getTableName();
    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = "select *  from "+tableName+" t1 where del_flg=0 and user_id="+THIS.user_id;
        sql+=" ORDER BY update_time DESC, img_id DESC  ";
        if(typeof skipCnt!='undefined' && skipCnt != null && typeof pageSize!='undefined' && pageSize != null){
            sql += " limit " + Number(skipCnt) + "," + Number(pageSize);
        }
        var sqlValue = [];
        var sql = mysql.format(sql, sqlValue);
        console.log(sql);

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });
}

// 导出
module.exports = ItbImageModel;